use tauri::AppHandle;
use serde::{Deserialize, Serialize};
use crate::storage;

/// 群组信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Group {
    pub group_id: String,
    pub owner_id: String,
    pub group_type: i32,
    pub group_name: String,
    pub mute: Option<i32>,
    pub apply_join_type: i32,
    pub avatar: Option<String>,
    pub max_member_count: Option<i32>,
    pub introduction: Option<String>,
    pub notification: Option<String>,
    pub status: Option<i32>,
    pub sequence: Option<i32>,
    pub create_time: Option<i64>,
    pub update_time: Option<i64>,
    pub extra: Option<String>,
    pub version: Option<i32>,
    pub del_flag: i32,
    pub verifier: Option<i16>,
    pub member_count: Option<i32>,
}

/// 群组成员信息
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GroupMember {
    pub group_member_id: String,
    pub group_id: String,
    pub member_id: String,
    pub role: i32,
    pub speak_date: Option<i64>,
    pub mute: i32,
    pub alias: Option<String>,
    pub join_time: Option<i64>,
    pub leave_time: Option<i64>,
    pub join_type: Option<String>,
    pub extra: Option<String>,
    pub del_flag: i32,
    pub create_time: Option<i64>,
    pub update_time: Option<i64>,
    pub version: Option<i32>,
}

/// 获取群组列表的缓存键
fn get_groups_cache_key() -> String {
    "user_groups".to_string()
}

/// 获取群组成员列表的缓存键
fn get_group_members_cache_key(group_id: &str) -> String {
    format!("group_members_{}", group_id)
}

/// 缓存群组列表
#[tauri::command]
pub async fn cache_user_groups(
    groups: Vec<Group>,
    app: AppHandle,
) -> Result<(), String> {
    let key = get_groups_cache_key();
    let json = serde_json::to_string(&groups)
        .map_err(|e| format!("序列化群组列表失败: {}", e))?;
    storage::secure_store_set(key, json, app).await
}

/// 获取缓存的群组列表
#[tauri::command]
pub async fn get_cached_user_groups(
    app: AppHandle,
) -> Result<Option<Vec<Group>>, String> {
    let key = get_groups_cache_key();
    match storage::secure_store_get(key, app).await? {
        Some(json) => {
            let groups: Vec<Group> = serde_json::from_str(&json)
                .map_err(|e| format!("反序列化群组列表失败: {}", e))?;
            Ok(Some(groups))
        }
        None => Ok(None),
    }
}

/// 缓存群组成员列表
#[tauri::command]
pub async fn cache_group_members(
    group_id: String,
    members: Vec<GroupMember>,
    app: AppHandle,
) -> Result<(), String> {
    let key = get_group_members_cache_key(&group_id);
    let json = serde_json::to_string(&members)
        .map_err(|e| format!("序列化群成员列表失败: {}", e))?;
    storage::secure_store_set(key, json, app).await
}

/// 获取缓存的群组成员列表
#[tauri::command]
pub async fn get_cached_group_members(
    group_id: String,
    app: AppHandle,
) -> Result<Option<Vec<GroupMember>>, String> {
    let key = get_group_members_cache_key(&group_id);
    match storage::secure_store_get(key, app).await? {
        Some(json) => {
            let members: Vec<GroupMember> = serde_json::from_str(&json)
                .map_err(|e| format!("反序列化群成员列表失败: {}", e))?;
            Ok(Some(members))
        }
        None => Ok(None),
    }
}

/// 添加群组成员到本地缓存
#[tauri::command]
pub async fn add_group_member_to_cache(
    group_id: String,
    member: GroupMember,
    app: AppHandle,
) -> Result<(), String> {
    // 获取现有的成员列表
    let mut members = get_cached_group_members(group_id.clone(), app.clone())
        .await?
        .unwrap_or_default();
    
    // 检查成员是否已存在
    if members.iter().any(|m| m.member_id == member.member_id) {
        // 更新现有成员
        if let Some(existing) = members.iter_mut().find(|m| m.member_id == member.member_id) {
            *existing = member;
        }
    } else {
        // 添加新成员
        members.push(member);
    }
    
    // 保存更新后的成员列表
    cache_group_members(group_id, members, app).await
}

/// 从本地缓存移除群组成员
#[tauri::command]
pub async fn remove_group_member_from_cache(
    group_id: String,
    member_id: String,
    app: AppHandle,
) -> Result<(), String> {
    // 获取现有的成员列表
    let mut members = get_cached_group_members(group_id.clone(), app.clone())
        .await?
        .unwrap_or_default();
    
    // 移除成员
    members.retain(|m| m.member_id != member_id);
    
    // 保存更新后的成员列表
    cache_group_members(group_id, members, app).await
}

/// 清除群组列表缓存
#[tauri::command]
pub async fn clear_groups_cache(
    app: AppHandle,
) -> Result<(), String> {
    let key = get_groups_cache_key();
    storage::secure_store_remove(key, app).await
}

/// 清除指定群组的成员列表缓存
#[tauri::command]
pub async fn clear_group_members_cache(
    group_id: String,
    app: AppHandle,
) -> Result<(), String> {
    let key = get_group_members_cache_key(&group_id);
    storage::secure_store_remove(key, app).await
}

